<?php

declare(strict_types=1);

namespace app\common\logic;

use think\facade\Log;
use app\common\model\User as ModelUser;

use app\common\lib\Math as LibMath;
use app\common\lib\easywechat\Payment as LibPayment;

/**
 * 获取微信支付参数
 */
class Payment
{
    // +---------------------------------------------------------
    // | 微信支付
    // +---------------------------------------------------------

    /**
     * 创建开通会员订单
     *
     * @param array $data
     */
    public static function create(array $data)
    {
        // 使用示例
        // $data = [
        //     'total_fee' => 0.01,
        //     'openid'    => 'olCRt5W0cNgEh953SJBz20rio1fA',
        // ];
        // $result = LogicPayment::create($data);

        $uid    = mt_rand(1, 10);
        $scene  = mt_rand(1, 2);
        $paylog = Paylog::create($uid, $scene);
        try {
            $body = '开通会员';
            $result = app(LibPayment::class)->unify($data['openid'], $paylog->out_trade_no, $data['total_fee'], $body);
        } catch (\Throwable $th) {
            $errMsg = ['error' => $th->getMessage()];
            Log::write(encode($errMsg), 'payment'); // 错误日志
            fault($th->getMessage()); //抛出错误
        }
        return $result;
    }

    // +---------------------------------------------------------
    // | 企业付款到零钱
    // +---------------------------------------------------------

    /**
     * 用户提现
     *
     * @param int   $uid    用户id
     * @param float $amount 提现金额,单位:元
     */
    public static function toBalance(int $uid, float $amount)
    {
        // 用户信息
        $user = ModelUser::findOrEmpty($uid);
        $user->isEmpty() && fault('用户不存在');
        // 启动事务
        $user->startTrans();
        try {
            // 关联保存
            $user->accounts()->save([
                'amount' => $amount,
                'note'   => '提现',
                'status' => 1,
            ]);
            // 修改用户余额
            $user->save(['balance' => LibMath::sub($user->balance, $amount)]);
            // 执行提现,提现失败时会抛出异常,进行事务回滚
            app(LibPayment::class)->toBalance($user->openid, $amount);
            $user->commit();
        } catch (\Exception $e) {
            $user->rollback();
            fault($e->getMessage());
        }
    }
}
